<script>
import HzSafeArea from "@/components/layout/hz/hz-safe-area.vue";
import SelectUser from "@/components/selectUser/index.vue";
import {getGoodsDetail, addPackProductOrders, getPointsExchangeRatio} from '@/api/mall';
import {GetUserCoupons} from '@/api/homePage.js';

export default {
  name: "package",
  components: {HzSafeArea, SelectUser},
  data() {
    const today = this.getFormattedDate(new Date());
    const tomorrow = this.getFormattedDate(this.getTomorrowDate());
    const endLimit = this.getFormattedDate(this.getDateAfterDays(15));

    return {
      id: '',
      packageInfo: {
        name: '',
        price: 0,
        image: '',
        businessId: '',
        productId: '',
        productSpecId: '',
        packageItems: [] // 套餐中包含的商品项目
      },
      // 通用数据
      remark: '',
      // 酒店相关
      dateRange: [today, tomorrow],
      datePickerStart: today,
      datePickerEnd: endLimit,
      // 门票相关
      ticketDate: today,
      timeSlots: [],
      selectedTimeSlots: {}, // 记录每个门票项目选择的场次, key为项目索引，value为选中的场次索引
      // 通用
      guests: [],
      currentSelectedGuests: [],
      showUserSelector: false,
      // 优惠券相关数据
      hasCoupons: false,
      useCoupons: [],
      couponTotalDiscount: 0,
      // 价格动画
      lastTotalPrice: 0,
      // 积分相关
      pointsRatio: 1, // 积分兑换比例
      isPointsPayment: false // 是否使用积分支付
    }
  },
  computed: {
    // 计算住宿天数
    nightsCount() {
      if (!this.dateRange || this.dateRange.length !== 2) return 1;
      const start = new Date(this.dateRange[0]);
      const end = new Date(this.dateRange[1]);
      const diff = Math.abs(end - start);
      return Math.ceil(diff / (1000 * 60 * 60 * 24));
    },

    // 格式化入住日期
    checkInDate() {
      return this.formatDateObject(this.dateRange[0]);
    },

    // 格式化离店日期
    checkOutDate() {
      return this.formatDateObject(this.dateRange[1]);
    },

    // 格式化门票日期
    formatTicketDate() {
      if (!this.ticketDate) return '';
      const {month, day, weekDay} = this.formatDateObject(this.ticketDate);
      return `${month}月${day}日 ${weekDay}`;
    },

    // 计算总价
    totalPrice() {
      let totalPrice = 0;

      // 获取游客/住宿人数量
      const personCount = Math.max(1, this.guests.length);

      // 遍历所有套餐项目计算总价
      this.packageInfo.packageItems.forEach((item, index) => {
        // 根据不同类型计算价格
        let itemPrice = item.price * personCount;

        // 如果是酒店类型，需要乘以住宿天数
        if (item.type === 13) {
          itemPrice = itemPrice * this.nightsCount;
        }

        // 如果是门票类型且选择了场次，可能需要使用场次的价格
        if (item.type === 11 && this.selectedTimeSlots[index] !== undefined) {
          const selectedSlot = item.timeSlots[this.selectedTimeSlots[index]];
          if (selectedSlot && selectedSlot.price) {
            itemPrice = selectedSlot.price * personCount;
          }
        }

        totalPrice += itemPrice;
      });

      // 减去优惠券折扣 - 只在非积分模式下计算优惠券
      if (!this.isPointsPayment && this.couponTotalDiscount > 0) {
        totalPrice -= this.couponTotalDiscount;
        // 确保价格不低于0
        totalPrice = Math.max(0, totalPrice);
      }

      // 四舍五入保留两位小数
      totalPrice = Math.round(totalPrice * 100) / 100;

      return totalPrice;
    },

    // 计算积分总额
    totalPoints() {
      if (!this.isPointsPayment) return 0;
      return Math.round(this.totalPrice * this.pointsRatio);
    }
  },
  onLoad(options) {
    if (options) {
      this.id = options.id || '';
      // 判断是否使用积分支付
      this.isPointsPayment = options.integral === 'true' || options.integral === true;
    }
    // 设置导航栏标题
    uni.setNavigationBarTitle({title: '套餐预订'});

    // 如果是积分支付类型，获取积分比例
    if (this.isPointsPayment) {
      this.getPointsRatio();
    }

    // 初始化套餐信息
    this.init();

    // 获取优惠券信息 - 只在非积分模式下获取
    if (!this.isPointsPayment) {
      this.getCoupon();
    }
  },
  watch: {
    // 监听总价变化
    totalPrice(newVal, oldVal) {
      if (oldVal && newVal !== oldVal) {
        this.lastTotalPrice = parseFloat(oldVal);
      }
    }
  },
  methods: {
    // 格式化日期对象
    formatDateObject(dateStr) {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      const month = date.getMonth() + 1;
      const day = date.getDate();
      const weekDay = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][date.getDay()];
      return {month, day, weekDay};
    },

    // 初始化套餐数据
    async init() {
      try {
        uni.showLoading({
          title: '加载中...',
          mask: true
        });

        // 获取套餐详情
        const { Data } = await getGoodsDetail({Id: this.id});

        // 设置套餐基本信息
        this.packageInfo.name = Data.Name;
        this.packageInfo.price = Data.ShowPrice;
        this.packageInfo.image = Data.Img;
        this.packageInfo.businessId = Data.BusinessId;
        this.packageInfo.productId = Data.Id || Data.ProductId;
        this.packageInfo.productSpecId = Data.ProductSpecId;

        // 处理套餐中的子产品 - 使用PackProductItems
        if (Data.PackProductItems && Array.isArray(Data.PackProductItems)) {
          // 处理套餐中的每个产品项目
          this.packageInfo.packageItems = Data.PackProductItems.map((item, index) => {
            // 根据产品类型处理特定数据
            if (item.Type === 11) { // 门票类型
              // 生成场次数据
              const timeSlots = this.generateTimeSlotsForItem(item);
              // 默认选择第一个可用场次
              const firstAvailableIndex = timeSlots.findIndex(slot => slot.available);
              if (firstAvailableIndex !== -1) {
                this.selectedTimeSlots[index] = firstAvailableIndex;
              }

              return {
                id: item.Id,
                name: item.Name,
                type: item.Type,
                price: item.ShowPrice || item.BusinessPrice,
                image: item.Img,
                timeSlots: timeSlots,
                productId: item.Id,
                productSpecId: item.ProductSpecId
              };
            } else if (item.Type === 13) { // 酒店类型
              return {
                id: item.Id,
                name: item.Name,
                type: item.Type,
                price: item.ShowPrice || item.BusinessPrice,
                image: item.Img,
                roomType: item.RoomType || '标准房',
                productId: item.Id,
                productSpecId: item.ProductSpecId
              };
            } else { // 其他类型
              return {
                id: item.Id,
                name: item.Name,
                type: item.Type,
                price: item.ShowPrice || item.BusinessPrice,
                image: item.Img,
                productId: item.Id,
                productSpecId: item.ProductSpecId
              };
            }
          });
        }

        uni.hideLoading();
      } catch (error) {
        uni.hideLoading();
        uni.showToast({
          title: '获取套餐信息失败',
          icon: 'none'
        });
      }
    },

    // 为门票类型生成场次数据
    generateTimeSlotsForItem(item) {
      // 如果没有规格列表，返回默认场次数据
      if (!item.ProductSpecList || !Array.isArray(item.ProductSpecList) || item.ProductSpecList.length === 0) {
        return [{
          id: null,
          startTime: '全天可用',
          endTime: '',
          price: item.ShowPrice || item.BusinessPrice,
          available: true,
          productSpecId: null
        }];
      }

      // 处理场次数据
      return item.ProductSpecList.map(spec => {
        return {
          id: spec.Id,
          startTime: spec.StartTime || '00:00',
          endTime: spec.EndTime || '23:59',
          price: spec.Price || item.ShowPrice || item.BusinessPrice,
          available: true,
          productSpecId: spec.Id
        };
      });
    },

    // 选择门票场次
    selectTimeSlot(itemIndex, slotIndex) {
      // 检查场次是否可用
      const item = this.packageInfo.packageItems[itemIndex];
      if (!item || !item.timeSlots[slotIndex].available) {
        uni.showToast({
          title: '该场次不可用',
          icon: 'none'
        });
        return;
      }

      this.selectedTimeSlots[itemIndex] = slotIndex;
    },

    // 门票日期变更
    onTicketDateChange(date) {
      this.ticketDate = date;

      // 刷新所有门票类型商品的场次
      this.packageInfo.packageItems.forEach((item, index) => {
        if (item.type === 11) {
          // 重新生成场次数据
          item.timeSlots = this.generateTimeSlotsForItem(item);

          // 默认选择第一个可用场次
          const firstAvailableIndex = item.timeSlots.findIndex(slot => slot.available);
          if (firstAvailableIndex !== -1) {
            this.selectedTimeSlots[index] = firstAvailableIndex;
          }
        }
      });
    },

    // 获取用户优惠券
    async getCoupon() {
      try {
        const { Data } = await GetUserCoupons({
          Index: 1,
          Size: 100,
          BusinessId: this.packageInfo.businessId,
          CouponStatus: 1
        });

        if (!Data || !Array.isArray(Data)) {
          this.hasCoupons = false;
          return;
        }

        const currentDate = Date.now();

        // 筛选有效优惠券
        const validCoupons = Data.filter(coupon => {
          const startTime = Date.parse(coupon.EffectStartDatetime);
          const endTime = Date.parse(coupon.EffectEndDatetime);
          return currentDate < endTime && currentDate > startTime;
        });

        // 设置是否有可用优惠券
        this.hasCoupons = validCoupons.length > 0;

      } catch (error) {
        this.hasCoupons = false;
      }
    },

    // 跳转到优惠券选择页面
    navigateToCoupons() {
      // 准备传递的参数
      const params = {
        businessId: this.packageInfo.businessId,
        totalPrice: this.totalPrice,
        productId: this.packageInfo.productId,
        selectedCoupons: this.useCoupons || []
      };

      // 跳转到优惠券页面
      uni.navigateTo({
        url: '/mall_subpages/goods/coupons?params=' + encodeURIComponent(JSON.stringify(params))
      });
    },

    // 从优惠券页面返回时接收数据
    onCouponSelected(coupons) {
      this.lastTotalPrice = this.totalPrice;
      this.useCoupons = coupons || [];

      // 计算优惠券总折扣金额
      this.calculateCouponDiscount();
    },

    // 计算优惠券总折扣金额
    calculateCouponDiscount() {
      if (!this.useCoupons || this.useCoupons.length === 0) {
        this.couponTotalDiscount = 0;
        return;
      }

      let totalDiscount = 0;
      const originalPrice = parseFloat(this.totalPrice);

      this.useCoupons.forEach(coupon => {
        if (coupon.CouponTemple && coupon.CouponTemple.FullReduceAmount) {
          totalDiscount += parseFloat(coupon.CouponTemple.FullReduceAmount);
        }
      });

      // 确保折扣不超过总价
      this.couponTotalDiscount = Math.min(totalDiscount, originalPrice);
    },

    // 构建优惠券参数
    buildCouponParams() {
      if (!this.useCoupons || this.useCoupons.length === 0) {
        return [];
      }

      return this.useCoupons.map(coupon => ({
        CouponCode: coupon.CouponCode,
        BusinessId: coupon.BusinessIds ? this.packageInfo.businessId : 0
      }));
    },

    // 获取格式化的日期字符串 YYYY-MM-DD
    getFormattedDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },

    // 获取明天的日期对象
    getTomorrowDate() {
      const date = new Date();
      date.setDate(date.getDate() + 1);
      return date;
    },

    // 获取指定天数后的日期对象
    getDateAfterDays(days) {
      const date = new Date();
      date.setDate(date.getDate() + days);
      return date;
    },

    // 用户选择相关方法
    openUserSelector() {
      this.currentSelectedGuests = [...this.guests];
      this.$refs.userSelector.open();
    },

    closeUserSelector() {
      this.$refs.userSelector.close();
    },

    onClearSelection() {
      this.guests = [];
    },

    onSelectComplete() {
      this.closeUserSelector();
    },

    onUserSelected(userData) {
      const existingIndex = this.guests.findIndex(guest => guest.idCard === userData.idCard);

      if (existingIndex === -1) {
        this.guests.push(userData);
      }
    },

    removeGuest(index) {
      this.guests.splice(index, 1);
    },

    // 验证订单数据
    validateOrderData() {
      // 检查是否有酒店或门票类型的产品
      const hasHotel = this.packageInfo.packageItems.some(item => item.type === 13);
      const hasTicket = this.packageInfo.packageItems.some(item => item.type === 11);

      // 验证入住人/游客信息
      if ((hasHotel || hasTicket) && this.guests.length === 0) {
        uni.showToast({
          title: '请至少添加一位入住人/游客',
          icon: 'none'
        });
        return false;
      }

      // 检查必要的商品信息是否存在
      if (!this.packageInfo.businessId || !this.packageInfo.productId) {
        uni.showToast({
          title: '套餐信息不完整',
          icon: 'none'
        });
        return false;
      }

      return true;
    },

    // 构建订单参数
    buildOrderParams() {
      // 构建基本订单参数
      const orderParams = {
        ProductId: this.packageInfo.productId,
        ProductName: this.packageInfo.name,
        ProductType: 17, // 套餐类型
        Price: this.packageInfo.price,
        PayStatus: 0,
        Point: 0,
        Count: 1, // 套餐数量默认为1
        Deposit: 0,
        ContactMobile: '',
        ContactName: '',
        CouponDiscount: this.couponTotalDiscount,
        OriginalPrice: this.packageInfo.price,
        PlatformType: 20, // 小程序
        SettleType: 1,
        payType: 0,
        IsTicket: 1, // 电子票
        OrderRemak: this.remark || '',
        BusinessId: this.packageInfo.businessId || 0,
        Persons: [],
        // 套餐特有参数
        PackProductItems: []
      };

      // 处理入住人/游客信息
      if (this.guests && this.guests.length > 0) {
        orderParams.Persons = this.guests.map(item => ({
          Name: item.name,
          Mobile: item.phone || '',
          IDCard: item.idCard
        }));
      }

      // 获取游客/住宿人数量
      const personCount = Math.max(1, this.guests.length);

      // 构建套餐子项目信息
      this.packageInfo.packageItems.forEach((item, index) => {
        const packItem = {
          ProductId: item.productId,
          ProductName: item.name,
          ProductType: item.type,
          Price: item.price,
          Count: personCount, // 使用游客/住宿人数量
          ProductSpecId: item.productSpecId
        };

        // 根据不同类型添加特定参数
        if (item.type === 11) { // 门票类型
          const selectedSlotIndex = this.selectedTimeSlots[index];
          if (selectedSlotIndex !== undefined && item.timeSlots && item.timeSlots[selectedSlotIndex]) {
            const selectedSlot = item.timeSlots[selectedSlotIndex];
            packItem.TicketDate = this.ticketDate;
            packItem.TicketStartTime = selectedSlot.startTime;
            packItem.TicketEndTime = selectedSlot.endTime;
            packItem.ProductSpecId = selectedSlot.productSpecId;
            if (selectedSlot.sceneId) {
              packItem.SceneId = selectedSlot.sceneId;
            }
          }
        } else if (item.type === 13) { // 酒店类型
          packItem.StartTime = this.dateRange[0];
          packItem.EndTime = this.dateRange[1];
          packItem.Days = Number(this.nightsCount);
          packItem.RoomCount = personCount; // 房间数量等于入住人数
        }

        orderParams.PackProductItems.push(packItem);
      });

      return orderParams;
    },

    // 获取积分比例
    async getPointsRatio() {
      try {
        const res = await getPointsExchangeRatio();
        const data = res.Data;
        this.pointsRatio = data.PointToCNYRatio;
      } catch (error) {
        this.pointsRatio = 1;
      }
    },

    // 提交订单
    async submitOrder() {
      // 验证订单数据
      if (!this.validateOrderData()) {
        return;
      }

      // 显示加载提示
      uni.showLoading({
        title: '提交中...',
        mask: true
      });

      try {
        // 构建订单参数
        const params = this.buildOrderParams();

        // 构建优惠券参数
        const useCoupons = this.isPointsPayment ? [] : this.buildCouponParams();

        // 组装最终请求参数
        const requestParams = {
          OrderProductList: [params],
          Coupons: useCoupons
        };

        // 如果是积分支付类型，添加UsePoints参数
        if (this.isPointsPayment) {
          requestParams.UsePoints = true;
        }

        // 调用套餐订单接口
        const { Data } = await addPackProductOrders(requestParams);

        // 隐藏加载提示
        uni.hideLoading();

        if (!Data || !Data.OrdersOnLineId) {
          uni.showToast({
            title: '订单创建成功，但未获取到订单ID',
            icon: 'none',
            duration: 2000
          });
          return;
        }

        if (this.isPointsPayment) {
          uni.redirectTo({
            url: `/mall_subpages/goods/success?id=${Data.OrdersOnLineId}&delta=1`
          });
        } else {
          // 跳转到支付页面
          uni.redirectTo({
            url: `/mall_subpages/goods/payment?id=${Data.OrdersOnLineId}&delta=2`
          });
        }
      } catch (error) {
        uni.hideLoading();
        uni.showToast({
          title: error.Msg || '提交订单失败',
          icon: 'none',
          duration: 2000
        });
      }
    },

    // 日期选择变更
    onDateChange(value) {
      if (!value || value.length !== 2) return;

      // 检查开始日期和结束日期是否相同
      if (value[0] === value[1]) {
        // 如果相同，则将结束日期设置为开始日期的后一天
        const startDate = new Date(value[0]);
        const nextDay = new Date(startDate);
        nextDay.setDate(nextDay.getDate() + 1);
        const nextDayFormatted = this.getFormattedDate(nextDay);

        // 更新日期范围
        this.dateRange = [value[0], nextDayFormatted];

        // 提示用户
        uni.showToast({
          title: '入住和离店日期不能相同',
          icon: 'none',
          duration: 2000
        });
        return;
      }

      // 日期合法，更新dateRange
      this.dateRange = value;
    }
  }
}
</script>

<template>
  <view class="package-container">

    <!-- 套餐基本信息 -->
    <view class="package-info">
      <view class="package-image">
        <image :src="packageInfo.image" mode="aspectFill"></image>
      </view>
      <view class="package-details">
        <view class="package-name">{{packageInfo.name}}</view>
        <view class="price" v-if="!isPointsPayment">¥{{packageInfo.price}}</view>
        <view class="price points-price" v-else>{{Math.round(packageInfo.price * pointsRatio)}} 积分</view>
      </view>
    </view>

    <!-- 套餐子项目信息 -->
    <view class="package-items" v-if="packageInfo.packageItems && packageInfo.packageItems.length > 0">
      <view class="section-title">套餐包含项目</view>

      <!-- 遍历套餐项目 -->
      <view
          class="package-item-card"
          v-for="(item, index) in packageInfo.packageItems"
          :key="index"
      >
        <!-- 项目标题 -->
        <view class="item-header">
          <view class="item-type-badge" :class="'type-' + item.type">
            <text v-if="item.type === 11">门票</text>
            <text v-else-if="item.type === 13">酒店</text>
            <text v-else>商品</text>
          </view>
          <view class="item-title">{{item.name}}</view>
        </view>

        <!-- 项目图片和信息 -->
        <view class="item-content">
          <view class="item-image">
            <image :src="item.image" mode="aspectFill"></image>
          </view>
          <view class="item-info">
            <view class="item-price-row">
              <text class="item-price">¥{{item.price}}</text>
              <view class="quantity-info">
                <text class="quantity-text">数量:{{Math.max(1, guests.length)}}份</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 酒店类型特有信息 -->
        <view class="item-specific-info" v-if="item.type === 13">
          <view class="hotel-info">
            <view class="room-type" v-if="item.roomType">{{item.roomType}}</view>

            <!-- 日期选择 -->
            <uni-datetime-picker
                type="range"
                v-model="dateRange"
                :clear-icon="false"
                :start="datePickerStart"
                :end="datePickerEnd"
                @change="onDateChange"
            >
              <view class="date-range-display">
                <view class="date-section">
                  <view class="date-label">入住日期</view>
                  <view class="date-content">
                    <text class="date-month">{{checkInDate.month}}月</text>
                    <text class="date-day">{{checkInDate.day}}日</text>
                    <text class="date-week">{{checkInDate.weekDay}}</text>
                  </view>
                </view>

                <view class="date-section">
                  <view class="date-label">离店日期</view>
                  <view class="date-content">
                    <text class="date-month">{{checkOutDate.month}}月</text>
                    <text class="date-day">{{checkOutDate.day}}日</text>
                    <text class="date-week">{{checkOutDate.weekDay}}</text>
                  </view>
                </view>

                <view class="nights-count">
                  <view class="night-badge">共{{nightsCount}}晚
                    <image src="/static/home/right-arrow-black.png"></image>
                  </view>
                </view>
              </view>
            </uni-datetime-picker>
          </view>
        </view>

        <!-- 门票类型特有信息 -->
        <view class="item-specific-info" v-if="item.type === 11">
          <view class="ticket-info">
            <!-- 使用日期 -->
            <view class="info-section">
              <view class="section-subtitle">使用日期</view>
              <uni-datetime-picker
                  type="date"
                  v-model="ticketDate"
                  :clear-icon="false"
                  :start="datePickerStart"
                  :end="datePickerEnd"
                  @change="onTicketDateChange"
              >
                <view class="ticket-date-display">
                  <view class="selected-date">
                    <text>{{formatTicketDate}}</text>
                    <uni-icons type="arrowright" size="16" color="#999"></uni-icons>
                  </view>
                </view>
              </uni-datetime-picker>
            </view>

            <!-- 场次选择 -->
            <view class="info-section" v-if="item.timeSlots && item.timeSlots.length > 0">
              <view class="section-subtitle">选择场次</view>
              <view class="time-slot-list">
                <view
                    v-for="(slot, slotIndex) in item.timeSlots"
                    :key="slotIndex"
                    class="time-slot-item"
                    :class="{
                    'selected-slot': selectedTimeSlots[index] === slotIndex,
                    'disabled-slot': !slot.available
                  }"
                    @click="selectTimeSlot(index, slotIndex)"
                >
                  <text>{{slot.startTime}}{{slot.endTime ? ' - ' + slot.endTime : ''}}</text>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 游客信息 -->
    <view class="guest-info">
      <view class="info-header">
        <view class="section-title">入住人/游客信息</view>
        <view class="add-guest-btn" @click="openUserSelector">
          <text class="add-icon">+</text>
          <text class="add-text">添加入住人/游客</text>
        </view>
      </view>

      <!-- 游客列表 -->
      <view class="guest-list">
        <view class="guest-item" v-for="(guest, index) in guests" :key="index">
          <view class="guest-index">游客{{index + 1}}</view>
          <view class="guest-details">
            <text class="guest-name">{{guest.name}}</text>
            <text class="id-number">- {{guest.idCard.substring(0, 11)}}</text>
            <text class="id-full">{{guest.idCard}}</text>
          </view>
          <view class="delete-btn" @click="removeGuest(index)">
            <text class="delete-icon">×</text>
          </view>
        </view>

        <!-- 没有游客时的提示 -->
        <view class="no-guest" v-if="guests.length === 0">
          <text class="no-guest-tip">请添加入住人/游客信息</text>
        </view>
      </view>
    </view>

    <!-- 备注 -->
    <view class="remarks">
      <view class="section-title">备注</view>
      <view class="input-wrapper">
        <input class="remark-input" type="text" v-model="remark" placeholder="请填写备注信息" placeholder-style="color: #999;"/>
      </view>
    </view>

    <!-- 优惠券区域 - 非积分模式才显示 -->
    <view class="coupon-area" v-if="!isPointsPayment">
      <view class="coupon-section">
        <view class="coupon-header">
          <view class="section-title">优惠券</view>
          <view class="coupon-status" v-if="useCoupons.length > 0">
            已选择{{useCoupons.length}}张，已优惠¥{{couponTotalDiscount.toFixed(2)}}
          </view>
          <view class="coupon-status available" v-else-if="hasCoupons">
            有可用优惠券
          </view>
          <view class="coupon-status unavailable" v-else>
            暂无可用优惠券
          </view>
        </view>
        <view class="coupon-selection" @click="navigateToCoupons">
          <view class="select-text">选择优惠券</view>
          <uni-icons type="forward" size="16" color="#BBBBBB"></uni-icons>
        </view>
      </view>
    </view>

    <!-- 预定须知 -->
    <view class="booking-notice">
      <view class="section-title">预定须知</view>
      <view class="notice-content">
        <text class="notice-text">
          预定须知内容
        </text>
      </view>
    </view>

    <hz-safe-area></hz-safe-area>

    <!-- 底部结算栏 -->
    <view class="bottom-bar">
      <view class="bottom-bar_inner">
        <view class="price-section">
          <text class="price-label" v-if="!isPointsPayment">订单金额 ¥</text>
          <text class="price-label" v-else>订单积分 </text>
          <template v-if="!isPointsPayment">
            <u-count-to
                class="total-price"
                ref="countTo"
                :start-val="Number(lastTotalPrice)"
                :end-val="Number(totalPrice)"
                :duration="1000"
                :decimals="2"
                :autoplay="true"
                :color="'#FF4B31'"
                :bold="true"
                :fontSize="28"
            ></u-count-to>
          </template>
          <template v-else>
            <text class="total-price points">{{totalPoints}}</text>
          </template>
        </view>
        <view class="submit-btn" @click="submitOrder">
          <text>提交订单</text>
        </view>
      </view>
      <hz-safe-area></hz-safe-area>
    </view>

    <!-- 用户选择弹窗 -->
    <uni-popup ref="userSelector" type="bottom">
      <view class="popup-content">
        <view class="popup-header">
          <text class="popup-title">选择入住人/游客</text>
          <text class="popup-close" @click="closeUserSelector">×</text>
        </view>
        <view class="popup-body">
          <select-user
              :selectedGuests="currentSelectedGuests"
              @select="onUserSelected"
              @clear="onClearSelection"
              @complete="onSelectComplete"
          ></select-user>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<style scoped lang="scss">
.package-container {
  padding: 30rpx 30rpx 100rpx;
  background-color: #F5F5F5;
  min-height: 100vh;
}

// 卡片组件
.package-info, .package-items, .guest-info,
.remarks, .booking-notice, .coupon-area {
  background-color: #FFF;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

// 套餐基本信息
.package-info {
  display: flex;
  align-items: center;

  .package-image {
    width: 160rpx;
    height: 160rpx;
    border-radius: 8rpx;
    overflow: hidden;
    margin-right: 20rpx;

    image {
      width: 100%;
      height: 100%;
    }
  }

  .package-details {
    flex: 1;

    .package-name {
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
      margin-bottom: 10rpx;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .price {
      font-size: 36rpx;
      color: #498FFF;
      font-weight: bold;
      margin-top: 10rpx;

      &.points-price {
        color: #FF4B31;
      }
    }
  }
}

// 套餐子项目
.package-items {
  .section-title {
    font-size: 30rpx;
    font-weight: 500;
    color: #333;
    margin-bottom: 20rpx;
  }

  .package-item-card {
    background-color: #FAFAFA;
    border-radius: 8rpx;
    padding: 20rpx;
    margin-bottom: 20rpx;

    .item-header {
      display: flex;
      align-items: center;
      margin-bottom: 15rpx;

      .item-type-badge {
        padding: 4rpx 12rpx;
        border-radius: 4rpx;
        font-size: 22rpx;
        margin-right: 10rpx;

        &.type-11 {
          background-color: #FFE4E1;
          color: #FF6347;
        }

        &.type-13 {
          background-color: #E6F7FF;
          color: #1890FF;
        }

        &.type-17 {
          background-color: #F0F5FF;
          color: #597EF7;
        }
      }

      .item-title {
        font-size: 28rpx;
        font-weight: 500;
        color: #333;
      }
    }

    .item-content {
      display: flex;
      margin-bottom: 15rpx;

      .item-image {
        width: 120rpx;
        height: 120rpx;
        border-radius: 6rpx;
        overflow: hidden;
        margin-right: 15rpx;

        image {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }

      .item-info {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: space-between;

        .item-price-row {
          display: flex;
          align-items: center;
          justify-content: space-between;

          .item-price {
            font-size: 30rpx;
            color: #FF4B31;
            font-weight: 500;
          }
        }
      }
    }

    .item-specific-info {
      margin-top: 15rpx;
      border-top: 1rpx dashed #EEE;
      padding-top: 15rpx;
    }
  }
}

// 游客信息
.guest-info {
  .info-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;

    .add-guest-btn {
      display: flex;
      align-items: center;
      background-color: #f8f8f8;
      padding: 6rpx 16rpx;
      border-radius: 30rpx;

      .add-icon {
        font-size: 28rpx;
        color: #498FFF;
        margin-right: 6rpx;
      }

      .add-text {
        color: #498FFF;
        font-size: 24rpx;
      }
    }
  }

  .guest-list {
    .guest-item {
      display: flex;
      align-items: center;
      padding: 20rpx 0;
      border-bottom: 1rpx solid #eee;

      &:last-child {
        border-bottom: none;
      }

      .guest-index {
        font-size: 28rpx;
        color: #666;
        margin-right: 20rpx;
        min-width: 80rpx;
      }

      .guest-details {
        flex: 1;

        .guest-name {
          font-size: 28rpx;
          color: #333;
        }

        .id-number {
          font-size: 28rpx;
          color: #666;
          margin-left: 10rpx;
        }

        .id-full {
          display: block;
          font-size: 24rpx;
          color: #999;
          margin-top: 6rpx;
        }
      }

      .delete-btn {
        width: 60rpx;
        height: 60rpx;
        display: flex;
        align-items: center;
        justify-content: center;

        .delete-icon {
          font-size: 36rpx;
          color: #ccc;
        }
      }
    }

    .no-guest {
      padding: 40rpx 0;
      text-align: center;

      .no-guest-tip {
        font-size: 28rpx;
        color: #999;
      }
    }
  }
}

// 标题样式
.section-title {
  font-size: 30rpx;
  font-weight: 500;
  color: #333;
  margin-bottom: 20rpx;
}

.section-subtitle {
  font-size: 26rpx;
  color: #666;
  margin-bottom: 10rpx;
}

// 输入框
.input-wrapper {
  background-color: #F5F5F5;
  border-radius: 8rpx;
  padding: 20rpx;

  .remark-input {
    width: 100%;
    font-size: 28rpx;
    color: #333;
  }
}

// 日期选择
.date-range-display {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  padding: 15rpx 0;
  background-color: #F8F8F8;
  border-radius: 8rpx;
  margin-top: 10rpx;
  padding: 20rpx;
}

.date-section {
  flex: 1;

  .date-label {
    font-size: 24rpx;
    color: #666;
    margin-bottom: 10rpx;
  }

  .date-content {
    display: flex;
    align-items: baseline;

    .date-day, .date-month {
      font-size: 26rpx;
      color: #333;
      font-weight: bold;
    }

    .date-week {
      font-size: 24rpx;
      color: #666;
      margin-left: 10rpx;
    }
  }
}

.nights-count {
  padding-left: 20rpx;

  .night-badge {
    font-size: 24rpx;
    color: #666;

    image {
      height: 24rpx;
      width: 13rpx;
      margin-left: 10rpx;
    }
  }
}

// 门票日期和场次选择
.ticket-date-display {
  display: flex;
  align-items: center;
  background-color: #F5F5F5;
  padding: 20rpx;
  border-radius: 8rpx;
}

.selected-date {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  font-size: 28rpx;
  color: #333;
}

.info-section {
  margin-bottom: 20rpx;

  &:last-child {
    margin-bottom: 0;
  }
}

.time-slot-list {
  display: flex;
  flex-wrap: wrap;
  margin-top: 10rpx;
}

.time-slot-item {
  width: 48%;
  height: 70rpx;
  line-height: 70rpx;
  text-align: center;
  background-color: #F5F5F5;
  border-radius: 8rpx;
  margin-bottom: 15rpx;
  color: #333;
  font-size: 26rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  padding: 0 10rpx;
  box-sizing: border-box;

  &:nth-child(odd) {
    margin-right: 4%;
  }

  &.selected-slot {
    background-color: #498FFF;
    color: #FFF;
  }

  &.disabled-slot {
    background-color: #f5f5f5;
    color: #aaaaaa;
    border: 1px dashed #dddddd;
  }
}

// 优惠券区域
.coupon-area {
  background-color: #FFF;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.coupon-section {
  .coupon-header {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;

    .section-title {
      margin-bottom: 0;
      margin-right: 20rpx;
    }

    .coupon-status {
      flex: 1;
      font-size: 24rpx;
      color: #498FFF;

      &.available {
        color: #498FFF;
      }

      &.unavailable {
        color: #999;
      }
    }
  }

  .coupon-selection {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 80rpx;
    padding: 0 20rpx;
    background-color: #F5F5F5;
    border-radius: 8rpx;

    .select-text {
      font-size: 28rpx;
      color: #666;
    }
  }
}

// 须知内容
.notice-text {
  font-size: 26rpx;
  color: #666;
  line-height: 1.6;
}

// 底部栏
.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #FFF;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);

  .bottom-bar_inner {
    display: flex;
    height: 100rpx;
    align-items: center;
    padding: 0 30rpx;
    width: 100%;
  }

  .price-section {
    flex: 1;
    display: flex;
    align-items: baseline;

    .price-label {
      font-size: 26rpx;
      color: #666;
    }

    .total-price {
      font-size: 40rpx;
      color: #498FFF;
      font-weight: bold;

      &.points {
        color: #FF4B31;
      }
    }
  }

  .submit-btn {
    background: linear-gradient(135deg, #498FFF 0%, #3A7FE6 100%);
    border-radius: 40rpx;
    height: 80rpx;
    padding: 0 50rpx;
    display: flex;
    align-items: center;
    justify-content: center;

    text {
      color: #FFF;
      font-size: 30rpx;
      font-weight: 500;
    }
  }
}

// 弹窗样式
.popup-content {
  width: 100%;
  background-color: #FFF;
  border-radius: 12rpx 12rpx 0 0;
  overflow: hidden;

  .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx;
    border-bottom: 1rpx solid #eee;

    .popup-title {
      font-size: 32rpx;
      font-weight: 500;
      color: #333;
    }

    .popup-close {
      font-size: 40rpx;
      color: #999;
      line-height: 1;
    }
  }

  .popup-body {
    max-height: 800rpx;
    overflow-y: auto;
  }
}

.quantity-info {
  font-size: 24rpx;
  color: #999;
  padding: 6rpx 12rpx;
  background-color: #f5f5f5;
  border-radius: 20rpx;

  .quantity-text {
    font-size: 24rpx;
    color: #666;
  }
}
</style>